# encoding:utf-8

import requests
import base64
import json
import pandas as pds
import os
from com.watermelon.rpa.functions import invoice_config
from com.watermelon.rpa.receipt_obj.ReceiptConvertObj import *

#获取pdf文件，并返回pdf文件路径+fileName
def obtain_pdf_file(pdfFilePath):
    listArr = []
    allFile = os.listdir(pdfFilePath)
    for file in allFile:
        if os.path.isfile(os.path.join(pdfFilePath,file)) and os.path.splitext(file)[1].lower() == ".pdf":
            listArr.append(pdfFilePath+"\\"+file)
    return listArr

#获取Access_token
def obtain_Access_token():
    url = f"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={invoice_config.API_Key}&client_secret={invoice_config.Secret_Key}"

    payload = ""
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)

    return json.loads(response.text)

#获取解析数据
def invoice_identify(token,filePath,file_Type):
    invoiceArr = []
    for i in range(len(filePath)):
        request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice"
        # 二进制方式打开图片文件
        f = open(filePath[i], 'rb')
        img = base64.b64encode(f.read())

        params = {file_Type: img}
        access_token = token
        request_url = request_url + "?access_token=" + access_token
        headers = {'content-type': 'application/x-www-form-urlencoded'}
        response = requests.post(request_url, data=params, headers=headers)
        if response:
            invoiceArr.append(response.json()["words_result"])
    return invoiceArr

#封装数据
def data_adapter(jsonDataArr):
    invoice = Invoice
    return dict_to_invoice(invoice, jsonDataArr)


#写入数据
def write_excel(excelFilePathName,writeData):
    if os.path.exists(excelFilePathName):
        fwrite = pds.DataFrame(writeData)
        fwrite.to_excel(excelFilePathName, index=False)
    else:
        open(excelFilePathName, "w").close()
        fwrite = pds.DataFrame(writeData)
        fwrite.to_excel(excelFilePathName, index=False)

#读取excel文件内容
def read_excel(filePathName):
    excelFileData = pds.read_excel(filePathName)
    return excelFileData.to_dict("list")


excelFile = r"D:\Dot\RPA\FourteenDay\receipt.xlsx"
filePath = r"D:\sutdy-Rpa-file\13课"
file_Type = "pdf_file"

#access_token = obtain_Access_token()["access_token"]

#文件路径列表
#pdfFilePathArr = obtain_pdf_file(filePath)

#解析票据
#resultArr = invoice_identify(access_token,pdfFilePathArr,file_Type)

#获取写入Excel的数据
#result = data_adapter(resultArr)

#写入excel数据
#write_excel(excelFile,result)

#读取excel文件内容
print(read_excel(excelFile))
